/*
 * TrackerConnectionPool.cpp
 *
 *  Created on: 2013年7月30日
 *      Author: sun
 */

#include "TrackerConnectionPool.h"
#include "../common/Log.h"

namespace sdfs {

const TrackerConnectionPool* TrackerConnectionPool::instance = NULL;

TrackerConnectionPool::TrackerConnectionPool(ServerConfig *confs,
		int serverSize, int poolsize, bool isBlock) {
	if(instance != NULL)
		return;
	m_nSize = serverSize;
	m_nPoolsize = poolsize;
	m_socket_pool =  new ConnectionPool*[m_nSize];
	m_registetable = new fdpair[m_nSize];
	m_bBlock = isBlock;
	for(int i = 0 ; i < m_nSize ; ++i)
	{
		Log::Debug("building connect: %s, count:%d", confs[i].strName, m_nPoolsize);
		Socket socket(&confs[i]);
		m_socket_pool[i] = new ConnectionPool(&socket, m_nPoolsize, isBlock);
		strcpy(m_registetable[i].name, confs[i].strName);
		m_registetable[i].index = i;
	}
	instance = this;
}

TrackerConnectionPool::~TrackerConnectionPool() {
	for(int i = 0 ; i < m_nSize ; ++i)
	{
		delete m_socket_pool[i];
	}
	Log::Debug("delete m_pools");
	delete []m_socket_pool;
	delete []m_registetable;
}

Socket *TrackerConnectionPool::GetConnection(const char* name)
{
	int index = GetIndex(name);
	if(index < 0)
		return NULL;
	return (Socket *)(m_socket_pool[index]->GetConnection());
}

int TrackerConnectionPool::ReturnConnection(Socket *socket)
{
	int idx = GetIndex(socket->GetServerName());
	if(idx < 0)
		return -1;
	return m_socket_pool[idx]->ReturnConnection(socket);
}

int TrackerConnectionPool::GetIndex(const char* name)
{
	for(int i = 0 ; i < m_nSize; i++)
	{
		if(strcmp(m_registetable->name, name) == 0)
			return i;
	}
	return -1;
}

TrackerConnectionPool * TrackerConnectionPool::GetInstance()
{
	return (TrackerConnectionPool *)instance;
}

} /* namespace sdfs */
